package com.stylefeng.guns.core.base.controller;

import com.alibaba.fastjson.JSONException;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.exception.FrontException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/2/6
 * Time: 10:56
 */
public class FrontBaseController {
    private final static Logger _log = LoggerFactory.getLogger(BaseController.class);
    @ExceptionHandler
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        request.setAttribute("ex", exception);
        if (null != request.getHeader("X-Requested-With") && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
            request.setAttribute("requestHeader", "ajax");
        }
        //预计中的异常
        if (exception instanceof FrontException) {
            _log.warn("可捕获的异常处理：", exception);
            return new ErrorTip(((FrontException) exception).getCode(), exception.getMessage());
        }
        if (exception instanceof NullPointerException || exception instanceof JSONException) {
            _log.error("统一异常处理：", exception);
            return new ErrorTip(400,"参数格式错误或该数据不存在！");
        }
        //预计外的异常
        _log.error("统一异常处理：", exception);
        return new ErrorTip(500, "操作失败");
    }

}
